import { INFO, CHUNK_SIZE, BASE_URL } from './config'
import axios from 'axios';
import md5 from 'md5';
; ((win, doc) => {
    const oProgress = document.querySelector('#progress'),
        oInfo = document.querySelector('#info'),
        oUploadInput = document.querySelector('#uploadInput'),
        oUploadBtn = document.querySelector('#uploadBtn');

    // 可变量
    let curUploadedSize = 0;
    let loop = true

    function init() {
        bindEvent()
    }


    function bindEvent() {
        /**
         * addEventListener
         * 
         * 事件类型
         * 事件处理程序
         * 如果是对象  那就是{passive once} passive如果为true  preventDefault被调用时会出现JS类型错误
         * 如果是boolean false就是冒泡事件  true就是捕获事件
         */
        oUploadBtn.addEventListener('click', uploadVideo, false)

        oUploadInput.addEventListener('change', (ev) => {
            const { files: [file] } = ev.target
            oProgress.setAttribute('max', file.size)
            if (localStorage.getItem(`${file.name}-curUploadedSize`)) {
                curUploadedSize = parseInt(localStorage.getItem(`${file.name}-curUploadedSize`))
                oProgress.setAttribute('value', curUploadedSize)
            }
        }, false)
    }

    async function uploadVideo() {
        const files = oUploadInput.files
        if (!files.length) {
            oInfo.innerText = INFO['NOT_FILE'];
            return;
        }
        const file = files[0]
        const { name, size, type } = file
        if (localStorage.getItem(`${name}-curUploadedSize`)) {
            curUploadedSize = parseInt(localStorage.getItem(`${name}-curUploadedSize`))
        }
        // 切片 分段上传
        while (curUploadedSize < size && loop) {
            // file.slice  3个参数  start end filetype
            const chunk = file.slice(curUploadedSize, curUploadedSize + CHUNK_SIZE);
            const hash = md5(chunk)

            const fileName = `${hash}-${name.substring(0, name.lastIndexOf('.'))}`
            const formData = createFormData({
                uploadSize: curUploadedSize,
                chunkSize: CHUNK_SIZE,
                name,
                fileName,
                size,
                type,
                file: chunk,
            })
            const res = await axios.post(BASE_URL + 'video-uplaod', formData)
            if (res.data.code == 200) {
                localStorage.setItem(`${name}-curUploadedSize`, curUploadedSize)
                curUploadedSize += CHUNK_SIZE
                oProgress.setAttribute('value', curUploadedSize)
            } else {
                loop = false
            }
        }

        if (curUploadedSize >= size) {
            localStorage.removeItem(`${name}-curUploadedSize`);
            curUploadedSize = 0;
        }
    }

    function createFormData(data) {
        const formData = new FormData()
        Object.keys(data).forEach(key => {
            formData.append(key, data[key])
        })
        return formData
    }

    init()
})(window, document)



